package com.aurora.source.home.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aurora.source.R;
import com.aurora.source.base.BaseLazyFragment;
import com.aurora.source.base.PhotoViewActivity;
import com.aurora.source.entity.SysPermissionEntity;
import com.aurora.source.home.adapter.QualificationHonorAdapter;
import com.aurora.source.home.bean.ContactUsDataBean;
import com.aurora.source.home.presenter.ContactUsPresenter;
import com.aurora.source.home.view.IContactUsView;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.GreenDaoHelper;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.ItemDivider;
import com.aurora.source.widget.RxDialogEditSureCancel;
import com.aurora.source.widget.RxDialogSureCancel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @author: pipi
 * @description: 资质荣誉
 * @date: 2018/9/7
 * @version: 1.0
 */
public class QualificationHonorFragment extends BaseLazyFragment<ContactUsPresenter> implements IContactUsView {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    Unbinder unbinder;
    private QualificationHonorAdapter qualificationHonorAdapter;
    String companyId;//公司id
    Map<String,String> editParams;//更换图片参数
    ContactUsDataBean.CompanyHonorDTOListBean companyHonorDTOListBean;//需要修改的数据项
    private boolean updateCompany = true;

    @Override
    public void doLazyBusiness() {
        refreshUI();
    }

    /**
     * 刷新UI
     */
    public void refreshUI(){
        Map<String, String> params = new HashMap<>();
        params.put("querySource", "0");
        params.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
        basePresenter.ContactUsSource(activity, params);
    }

    @Override
    public void invisibleBusiness() {

    }

    @Override
    public ContactUsPresenter attach() {
        return new ContactUsPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.fragment_qualification_honor;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        SysPermissionEntity sysPermissionEntity = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().loadAll().get(0);
        updateCompany = sysPermissionEntity.getUpdateCompany();
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {
        qualificationHonorAdapter = new QualificationHonorAdapter(activity,updateCompany);
        qualificationHonorAdapter.setOnAddImgClickListener(new QualificationHonorAdapter.OnAddImgClickListener() {
            @Override
            public void onAddImgClick() {
                if(!updateCompany){
                    showToast("暂无权限");
                    return;
                }
                if(qualificationHonorAdapter.getDatas().size()>4){
                    showToast("最多上传5张图片");
                    return;
                }
                companyHonorDTOListBean = new ContactUsDataBean.CompanyHonorDTOListBean();
                companyHonorDTOListBean.setCompanyHonorPath("");
                companyHonorDTOListBean.setImageId("-1");
                showAddPop();
            }
        });
        //修改图片
        qualificationHonorAdapter.setOnImgClickListener(new QualificationHonorAdapter.OnImgClickListener() {
            @Override
            public void onImgClick(ContactUsDataBean.CompanyHonorDTOListBean dtoListBean, int position) {

                ArrayList<String> images = new ArrayList<>();
                images.add(dtoListBean.getCompanyHonorPath());
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("images",images);
                bundle.putString("title","图片资源预览");
                bundle.putInt("position",position);
                gotoActivity(PhotoViewActivity.class,bundle);
            }
        });
        //修改图片名称
        qualificationHonorAdapter.setOnEditClickListener(new QualificationHonorAdapter.OnEditClickListener() {
            @Override
            public void onEditClick(ContactUsDataBean.CompanyHonorDTOListBean dtoListBean, int position) {
                if(!updateCompany){
                    showToast("暂无权限");
                    return;
                }
                companyHonorDTOListBean = dtoListBean;
                //修改图片名称
                showEditPop();
            }
        });
        //删除图片
        qualificationHonorAdapter.setOnDeleteClickListener(new QualificationHonorAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(ContactUsDataBean.CompanyHonorDTOListBean dtoListBean, int position) {
                if(!updateCompany){
                    showToast("暂无权限");
                    return;
                }
                companyHonorDTOListBean = dtoListBean;
                showDeletePop();
            }
        });
        recyclerView.setNestedScrollingEnabled(false);
        GridLayoutManager ridLayoutManager = new GridLayoutManager(getContext(), 2);
        recyclerView.setLayoutManager(ridLayoutManager);
        recyclerView.setAdapter(qualificationHonorAdapter);
        recyclerView.addItemDecoration(new ItemDivider().setDividerColor(Color.parseColor(getString(R.color.divider))).setDividerWith(DpPxUtil.dp2px(activity, 1)));

    }

    //删除图片确认弹窗
    private void showDeletePop() {
        final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(activity);
        rxDialogSureCancel.setTitle("提示");
        rxDialogSureCancel.setContent("是否确认删除图片");
        rxDialogSureCancel.setSureListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int updateType = 2;
                String deleteResourceId = companyHonorDTOListBean.getImageId();
                basePresenter.deleteCompanyResource(activity,updateType,companyId,deleteResourceId);
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.setCancelListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogSureCancel.cancel();
            }
        });
        rxDialogSureCancel.show();
    }

    //新增图片弹窗
    private void showAddPop() {
        final RxDialogEditSureCancel rxDialogEditSureCancel = new RxDialogEditSureCancel(activity);//提示弹窗
        //  rxDialogEditSureCancel.getTitleView().setBackgroundResource(R.drawable.log);
        rxDialogEditSureCancel.setTitle("请输入图片名称");
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = rxDialogEditSureCancel.getEditText().getText().toString();
                companyHonorDTOListBean.setImageTitle(content);
                //选择图片
                showPictureSelector(1,false);
                rxDialogEditSureCancel.cancel();
            }
        });
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogEditSureCancel.cancel();
            }
        });
        rxDialogEditSureCancel.show();
    }

    //修改名称弹窗
    private void showEditPop() {
        final RxDialogEditSureCancel rxDialogEditSureCancel = new RxDialogEditSureCancel(activity);//提示弹窗
      //  rxDialogEditSureCancel.getTitleView().setBackgroundResource(R.drawable.log);
        rxDialogEditSureCancel.getEditText().setText(companyHonorDTOListBean.getImageTitle());
        rxDialogEditSureCancel.setTitle("请输入图片名称");
        rxDialogEditSureCancel.getSureView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = rxDialogEditSureCancel.getEditText().getText().toString();
                companyHonorDTOListBean.setImageTitle(content);
                //选择图片
                showPictureSelector(1,false);
              /*  editParams = new HashMap<>();
                editParams.put("updateType","0");//0：荣誉资质;1:检疫报告
                editParams.put("companyId",companyId+"");
                editParams.put("deleteResourceId",companyHonorDTOListBean.getImageId()+"");
                editParams.put("imageTitle",content+"");
                basePresenter.upDataQualiImg(activity,editParams,null);*/
                rxDialogEditSureCancel.cancel();
            }
        });
        rxDialogEditSureCancel.getCancelView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rxDialogEditSureCancel.cancel();
            }
        });
        rxDialogEditSureCancel.show();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onContactUsSuccess(ContactUsDataBean data) {
        companyId = data.getCompanyId();
        qualificationHonorAdapter.setDatas(data.getCompanyHonorDTOList());
    }

    @Override
    public void onContactUsFail(String msg) {

    }

    @Override
    public void onUpDataFail(String msg) {
        showToast(msg);
    }

    //修改成功
    @Override
    public void onUpDataSuccess(String msg) {
        showToast(msg);
        refreshUI();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //修改资质图片
                    editParams = new HashMap<>();
                    editParams.put("updateType","0");//0：荣誉资质;1:检疫报告
                    editParams.put("companyId",companyId+"");
                    if(!companyHonorDTOListBean.getImageId().equals("-1")){//-1新增,其他修改
                        editParams.put("deleteResourceId",companyHonorDTOListBean.getImageId()+"");
                    }
                    editParams.put("imageTitle",companyHonorDTOListBean.getImageTitle()+"");
                    basePresenter.upDataQualiImg(activity,editParams,new File(selectList.get(0).getCompressPath()));
                    break;
            }
        }

    }
}
